package com.woniuxy.file.controller;

import com.aliyun.oss.OSSClient;
import com.woniuxy.commons.util.ResponseResult;
import com.woniuxy.file.entity.UploadResult;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.InputStream;
import java.net.URL;
import java.util.Date;
import java.util.UUID;

/**
 * @Author zhangyong
 * @Date 2021/8/6 0006下午 3:22
 */
@RestController
@RequestMapping("/file")
public class FileController {

    //springboot自动配置好了，直接拿来用
    @Resource
    private OSSClient ossClient;
    private String bucketName = "springcloud-79-zy";
    private String baseUrl="https://springcloud-79-zy.oss-cn-chengdu.aliyuncs.com";

    @PostMapping("/upload")
    public ResponseResult upload(MultipartFile file) throws Exception{
        //获取文件名字
        String filename = file.getOriginalFilename();
        //文件名需要处理，避免文件名一样造成文件覆盖
        String fileName = UUID.randomUUID().toString().replace("-","")+filename.substring(filename.lastIndexOf("."));

        //1.获取文件流对象
        InputStream inputStream = file.getInputStream();

        //2.将流设置到ossclient对象上
        ossClient.putObject(bucketName,fileName,inputStream);

        //3.设置文件过期时间
        Date date = new Date(new Date().getTime() + 1000 * 3600 * 24 * 30);

        //4.上传文件到阿里云
        URL url = ossClient.generatePresignedUrl(bucketName, fileName, date);

        //5.封装结果
        ResponseResult<UploadResult> responseResult = new ResponseResult<>();
        responseResult.setCode(200);
        responseResult.setMessage("上传成功");
        responseResult.setData(new UploadResult(fileName,baseUrl+url.getPath()));

        //返回结果

        return responseResult;
    }
}
